// Copyright 2021 the V8 project authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/*---
esid: sec-arraybuffer-length
description: >
  Automatically ported from FillParameterConversionResizes test
  in V8's mjsunit test typedarray-resizablearraybuffer.js
features: [resizable-arraybuffer]
flags: [onlyStrict]
---*/

function Test() {
    class MyUint8Array extends Uint8Array {
    }

    class MyFloat32Array extends Float32Array {
    }

    class MyBigInt64Array extends BigInt64Array {
    }

    const builtinCtors = [
      Uint8Array,
      Int8Array,
      Uint16Array,
      Int16Array,
      Uint32Array,
      Int32Array,
      Float32Array,
      Float64Array,
      Uint8ClampedArray,
      BigUint64Array,
      BigInt64Array
    ];

    const ctors = [
      ...builtinCtors,
      MyUint8Array,
      MyFloat32Array,
      MyBigInt64Array
    ];

    function CreateResizableArrayBuffer(byteLength, maxByteLength) {
      return new ArrayBuffer(byteLength, { maxByteLength: maxByteLength });
    }

    function TypedArrayFillHelper(ta, n, start, end) {
      if (ta instanceof BigInt64Array || ta instanceof BigUint64Array) {
        ta.fill(BigInt(n), start, end);
      } else {
        ta.fill(n, start, end);
      }
    }

    for (let ctor of ctors) {
      const rab = CreateResizableArrayBuffer(4 * ctor.BYTES_PER_ELEMENT, 8 * ctor.BYTES_PER_ELEMENT);
      const fixedLength = new ctor(rab, 0, 4);
      const evil = {
        valueOf: () => {
          rab.resize(2 * ctor.BYTES_PER_ELEMENT);
          return 3;
        }
      };
      assert.throws(TypeError, () => {
        TypedArrayFillHelper(fixedLength, evil, 1, 2);
      });
    }
    for (let ctor of ctors) {
      const rab = CreateResizableArrayBuffer(4 * ctor.BYTES_PER_ELEMENT, 8 * ctor.BYTES_PER_ELEMENT);
      const fixedLength = new ctor(rab, 0, 4);
      const evil = {
        valueOf: () => {
          rab.resize(2 * ctor.BYTES_PER_ELEMENT);
          return 1;
        }
      };
      assert.throws(TypeError, () => {
        TypedArrayFillHelper(fixedLength, 3, evil, 2);
      });
    }
    for (let ctor of ctors) {
      const rab = CreateResizableArrayBuffer(4 * ctor.BYTES_PER_ELEMENT, 8 * ctor.BYTES_PER_ELEMENT);
      const fixedLength = new ctor(rab, 0, 4);
      const evil = {
        valueOf: () => {
          rab.resize(2 * ctor.BYTES_PER_ELEMENT);
          return 2;
        }
      };
      assert.throws(TypeError, () => {
        TypedArrayFillHelper(fixedLength, 3, 1, evil);
      });
    }
}

// preheat
const NUMBER_OF_PREHEAT = 1;
for (let i = 0; i < NUMBER_OF_PREHEAT; i++) {
    Test();
}

ArkTools.jitCompileAsync(Test);
assert.sameValue(ArkTools.waitJitCompileFinish(Test), true, '[JIT] JIT disabled.');

// test
const NUMBER_OF_TEST = 1; // or 2
for (let i = 0; i < NUMBER_OF_TEST; i++) {
    Test();
}
